package cn.tkb.user.service.impl;

import cn.tkb.basic.exception.BusinessException;
import cn.tkb.basic.util.AjaxResult;
import cn.tkb.basic.util.HttpClientUtils;
import cn.tkb.basic.util.MD5Utils;
import cn.tkb.basic.util.StrUtils;
import cn.tkb.user.constant.UserConstants;
import cn.tkb.user.domain.LoginInfo;
import cn.tkb.user.domain.User;
import cn.tkb.user.domain.WxUser;
import cn.tkb.user.dto.LoginDto;
import cn.tkb.user.mapper.LoginInfoMapper;
import cn.tkb.user.mapper.UserMapper;
import cn.tkb.user.mapper.WxUserMapper;
import cn.tkb.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto dto) {
        //1.校验
        if(StringUtils.isEmpty(dto.getUsername())
                ||StringUtils.isEmpty(dto.getPassword())
                ||StringUtils.isEmpty(dto.getUsername())
                ||StringUtils.isEmpty(dto.getType())){
            throw new BusinessException("请填入必填项！！！");
        }
        //2.判断用户是否存在，存在比对密码是否正确
        //2.1查找用户
        LoginInfo info=loginInfoMapper.loadByUser(dto);
        if(info==null){
           throw new BusinessException("用户不存在，请注册！！！");
        }
        //比对密码
        String salt = info.getSalt();
        String Md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        if(!info.getPassword().equals(Md5Pwd)){
            throw new BusinessException("用户信息错误！！！");
        }
        //密码一致那么把登录信息和token存到redis当中设置30分钟后过期
        String token = UUID.randomUUID().toString();
        //去除登录信息中的敏感信息
        info.setSalt(null);
        info.setPassword(null);
        redisTemplate.opsForValue().set(token,info,30, TimeUnit.MINUTES);
        //把token和loginInfo的信息返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("loginInfo",info);
        return map;
    }

    /**
     * 微信三方扫码登录实现
     * @param params
     * @return
     */
    @Override
    public AjaxResult wechat(Map<String, String> params) {
        String code = params.get("code");
        //1.空校验
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("你的授权码出错了！！！");
        }
        //2.发送http请求获取accessToken 和openId
        String tokenResult = HttpClientUtils.httpGet(UserConstants.BUSINESS_TOKEN_URL
                .replace("APPID", UserConstants.APPID)
                .replace("SECRET", UserConstants.SECRET)
                .replace("CODE",code)
        );
        //处理http请求传递过来的json对象
        JSONObject jsonObject = JSONObject.parseObject(tokenResult);
        //通过授权码获得的令牌
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //3.通过openId查询t_Wxuser表里面是否有
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        if(wxUser!=null && wxUser.getUser_id()!=null){
            //说明我们平台有该用户的账户直接免密登录

            //这里没有loginInfo的信息要去数据库查该用户的登录信息
            LoginInfo info =loginInfoMapper.loadByUserId(wxUser.getUser_id());
            String token = UUID.randomUUID().toString();
            //去除登录信息中的敏感信息
            info.setSalt(null);
            info.setPassword(null);
            redisTemplate.opsForValue().set(token,info,30, TimeUnit.MINUTES);
            //把token和loginInfo的信息返回给前端
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("loginInfo",info);
            return AjaxResult.success().setResultObj(map);
        }
        //查询不到那么就走绑定流程把Token和openId传递给前端
        return AjaxResult.fail("?accessToken="+accessToken+"&openId="+openId);
    }

    /**
     * 微信三方扫码登录注册和绑定系统账号实现
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> binderWechat(Map<String, String> params) {
        //1.校验
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        if(StringUtils.isEmpty(phone)
                ||StringUtils.isEmpty(verifyCode)
                ||StringUtils.isEmpty(accessToken)
                ||StringUtils.isEmpty(openId)){
            throw new BusinessException("请填写必填项！！！");
        }
        //查询phone是否在本站有信息
        User user = userMapper.loadByPhone(phone);
        LoginInfo loginInfo =null;
        if(user!=null){//说明这个手机号在系统中我们只需要把Wxuser表中的数据和user绑定就行了
            loginInfo = loginInfoMapper.loadById(user.getLogininfo_id());
        }else{//说明这个手机号没有在我们系统中那么我们就走注册流程
            //3.验证码是否有效
            //获取验证码这里面是code+时间戳
            Object codeTmp = redisTemplate.opsForValue().get(UserConstants.BUSINESS_BINDER_PREFIX+ phone);
            if(codeTmp ==null){
                throw new BusinessException("请获取验证码！！！");
            }
            //4.验证码是否一致
            //获取验证码
            String code = codeTmp.toString().split(":")[0];
            if(!verifyCode.equalsIgnoreCase(code)){
                throw new BusinessException("验证码不一致请输入正确的验证码");
            }
            //5.判断该手机号是否被注册了
            user = userMapper.loadByPhone(phone);
            if(user!=null){
                //根据user的id查询到loginInfo信息返回给前端
                loginInfo = loginInfoMapper.loadByUserId(user.getId());
            }
            //6.注册成功保存数据
            //先保存loginInfo表然后再保存user表

            //先初始化user因为user里面只有一个phone没有密码
            user=initUser(phone);
            loginInfo =user2loginInfo(user);
            loginInfoMapper.save(loginInfo);//返回自增id
            //因为loginIn里面的信息和user里面的信息有重复的直接用loginInfo转
            user.setLogininfo_id(loginInfo.getId());
            userMapper.save(user);
        }
        //从微信获取用户的基本信息和平台的信息绑定
        String WxuserObject = HttpClientUtils.httpGet(UserConstants.BUSINESS_WxUser_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId)
        );
        WxUser wxUser= initWxUser(WxuserObject,user);
        wxUser.setUser_id(user.getId());
        wxUserMapper.save(wxUser);
        //5.免密登录
        //密码一致：存储redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,   //随机串
                loginInfo,    //登录成功的用户
                30,
                TimeUnit.MINUTES  //30分钟后过期
        );
        //4.3 返回token和logininfo基本信息给前端
        Map<String,Object> map =  new HashMap<>();
        map.put("token",token);
        //考虑细一点，我们不应该把敏感信息返回给前端 密码 salt
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo",loginInfo);
        return map;
    }

    /**
     * user转loginInfo
     * @param user
     * @return
     */
    private LoginInfo user2loginInfo(User user) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user,loginInfo);
        return loginInfo;
    }

    /**
     * 初始化user使用phone转user
     * @param phone
     * @return
     */
    private User initUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setUsername(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String password = MD5Utils.encrypByMd5("1" + salt);
        user.setSalt(salt);
        user.setPassword(password);
        return user;

    }

    /**
     * 初始化从微信拿到的jsonObject转为WxUser
     * @param WxuserObject
     * @param user
     * @return
     */
    private WxUser initWxUser(String WxuserObject, User user) {
        //转换微信用户信息
        JSONObject jsonObject = JSONObject.parseObject(WxuserObject);
        WxUser wxUser =  new WxUser();
        wxUser.setUser_id(user.getId());//绑定用户
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setAddress(null);
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        return wxUser;
    }

}
